from django.shortcuts import render

from rest_framework.views import APIView
from rest_framework.response import  Response
from rest_framework.permissions import IsAdminUser,DjangoModelPermissions
from datetime import date, timedelta
from users.models import User
from goods.models import GoodsVisitCount

class UserTotalCountView(APIView):
    permission_classes = [IsAdminUser,DjangoModelPermissions]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()

        # 获取所有用户的总数
        count = User.objects.all().count()
        return Response({
            'count':count,
            'date':now_date
        })

class UserDayCountView(APIView):
    permission_classes = [IsAdminUser,DjangoModelPermissions]

    def get(self,request):
        now_date=date.today()
        count=User.objects.filter(date_joined__gte=now_date).count()
        return Response({
            'count': count,
            'date': now_date
        })

class UserActiveCountView(APIView):
    permission_classes = [IsAdminUser,DjangoModelPermissions]

    def get(self,request):
        now_date = date.today()
        count= User.objects.filter(last_login__gte=now_date).count()
        return Response({
            'count':count,
            'date':now_date
        })

class UserOrderCountView(APIView):
    permission_classes = [IsAdminUser,DjangoModelPermissions]

    def get(self,request):
        now_date = date.today()
        count = User.objects.filter(orders__create_time__gte=now_date).count()
        return Response({
            'count':count,
            'date':now_date
        })

class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser,DjangoModelPermissions]

    def get(self,request):
        now_date = date.today()
        start_date = now_date - timedelta(30)
        data_list = []

        for i in range(31):
            first_date = start_date + timedelta(i)
            next_date = start_date + timedelta(i+1)
            count = User.objects.filter(date_joined__gte=first_date,date_joined__lt=next_date).count()
            data_list.append({
                'count':count,
                'date':first_date,
            })

        return Response(data_list)

class GoodsTypeCountView(APIView):
    permission_classes = [IsAdminUser,DjangoModelPermissions]

    def get(self,request):
        now_date = date.today()

        goodsvist = GoodsVisitCount.objects.filter(date__gte=now_date)
        data_list = []
        for goods in goodsvist:
            data_list.append({
                'count':goods.count,
                'category':goods.category.name
            })

        return Response(data_list)